'''
https://leetcode.cn/problems/design-a-leaderboard
'''

from sortedcontainers import SortedDict


class Leaderboard:

    def __init__(self):
        self.scores = {}
        self.sorted_scores = SortedDict()
        

    def addScore(self, playerId: int, score: int) -> None:
        if playerId in self.scores:
            old_score = self.scores[playerId]
            new_score = old_score + score
            self.scores[playerId] = new_score
            
            # Update the sorted scores
            if old_score in self.sorted_scores:
                self.sorted_scores[old_score].remove(playerId)
                if not self.sorted_scores[old_score]:
                    del self.sorted_scores[old_score]
            
            if new_score not in self.sorted_scores:
                self.sorted_scores[new_score] = set()
            self.sorted_scores[new_score].add(playerId)
        else:
            self.scores[playerId] = score
            if score not in self.sorted_scores:
                self.sorted_scores[score] = set()
            self.sorted_scores[score].add(playerId)
        

    def top(self, K: int) -> int:
        total_score = 0
        count = 0
        
        for score in reversed(self.sorted_scores):
            players = self.sorted_scores[score]
            for playerId in players:
                total_score += score
                count += 1
                if count == K:
                    return total_score
        
        return total_score
        

    def reset(self, playerId: int) -> None:
        if playerId in self.scores:
            score = self.scores[playerId]
            del self.scores[playerId]
            
            if score in self.sorted_scores:
                self.sorted_scores[score].remove(playerId)
                if not self.sorted_scores[score]:
                    del self.sorted_scores[score]
        
